import React, { Component } from 'react'
import { Carousel } from 'antd-mobile'
import { getSwiperList } from 'api/home.js'
import { BASE_URL } from 'utils/config.js'
import './index.scss'
export default class Index extends Component {
  state = {
    swiperList: [],
    // 设置稿 212/375 = x/屏幕宽度
    imgHeight: (212 / 375) * window.innerWidth,
  }
  async componentDidMount() {
    // 自己发送请求
    const { status, body } = await getSwiperList()
    if (status === 200) {
      // 请求成功
      this.setState({
        swiperList: body,
      })
    }
  }
  renderSwiper() {
    if (this.state.swiperList.length > 0) {
      return (
        <Carousel
          /*自动播放*/
          autoplay
          //无限滚动
          infinite
          // 面板指示点
          dots
          // 自动切换的时间
          autoplayInterval={3000}
        >
          {this.state.swiperList.map((item) => (
            <a
              key={item.id}
              href="{item.imgSrc}"
              style={{
                display: 'inline-block',
                width: '100%',
                height: this.state.imgHeight,
              }}
            >
              <img
                src={BASE_URL + item.imgSrc}
                alt={item.alt}
                style={{ width: '100%', verticalAlign: 'top' }}
                onLoad={() => {
                  // fire window resize event to change height
                  window.dispatchEvent(new Event('resize'))
                  this.setState({ imgHeight: 'auto' })
                }}
              />
            </a>
          ))}
        </Carousel>
      )
    } else {
      return null
    }
  }
  render() {
    return (
      <div className="index">
        {/* 轮播图 */}
        <div className="swiper" style={{ height: this.state.imgHeight }}>
          {this.renderSwiper()}
        </div>
      </div>
    )
  }
}
